package poswar.contribute.mbean;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.model.SelectItem;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import poswar.contribute.util.Config;

@ApplicationScoped
@ManagedBean
public class ContributeBean {
	private static final Logger LOG = Logger.getLogger(ContributeBean.class);
	
	private long lastPropertiesTimestamp;

	public ArrayList<SelectItem> getLinks() {
		ArrayList<SelectItem> list = new ArrayList<SelectItem>();
		
		List<String> lines = getLines();
		for (String entry: lines) {
			int index = entry.indexOf("=");
			String label = entry.substring(0, index);
			String value = entry.substring(index+1);
			
			SelectItem item = new SelectItem(value,label);
			list.add(item);	
		}
		
		return list;
	}

	private List<String> getLines() {
		List<String> list = new ArrayList<String>();
		
		File f = new File(Config.getLinksFilename());
		if (f.isFile() && f.lastModified() != lastPropertiesTimestamp) {
			LOG.info("Reading link file [" + Config.getLinksFilename() + "]");
			
			try {
				list = FileUtils.readLines(f);
				lastPropertiesTimestamp = f.lastModified();
			} catch (IOException e) {
				LOG.warn("Error loading link properties", e);
			}			
		}
		
		return list;
	}
}
